import utils from "../../common/utils/utils";
import request from "../../common/utils/request";
import * as storage from "../../common/utils/storage";

import {
  baseSubtitle,
  getSsmlcontent,
} from "@/views/shotstack/MuseMixedCut/utools/index.js";
import { message } from "ant-design-vue";

export const INITIAL_CLIP_JSON = {
  id: -1, // 剪辑id
  // 字幕
  subtitle_config: {
    open: 1,
    font: null,
    font_size: 32,
    material_url: null,
    width: 400,
    height: 200,
    css: "b {font-family:'TsangerXWZ';text-align:center}",
  },
  volume: {
    // 音量(注意，由于SDK音量是 0-1，所以前端传递必须是：0-100，然后使用的时候都要÷100)，必须
    bgm_volume: 50, // 背景音量 -对应 音乐 的 背景声音
    audio_volume: 100, // 音频音量--对应口播的解说音频
    scene_volume: 100, // 场景音量 --暂未对上号
    video_volume: 50, // 视频音量 --对应素材里的 视频原声
  },
  bgm_mode: "custom", // 背景音乐模式：custom-自定义，random-随机，必须
  bgm_scenes: [],
  bgm: [],
  // 口播
  audio: [],
  // 场景数据
  resource_data: [],
  effect_filter: {
    // 颜色调整
    color: {
      contrast: 0, // 对比度
      saturation: 0, // 饱和度
      brightness: 0, // 亮度
      tint: 0, // 色调
      temperature_ratio: 0, // 色温强度
      kelvin_temperature: 6000, // 色温
    },
  },
  //type  transition转场特效，filter滤镜特效
  effects: [],
  sticker_config: [],
  cover_config: [],
  // 文字
  whole_subtitle_config: [],
};

const shotstack = {
  state: {
    // 存储系统配置
    work_ai_config: {},

    editMode: 1, // 1-智能剪辑，2-一键成片，3-模板剪辑，4-脚本剪辑，5-图文剪辑）
    dragStatus: {}, //拖拽类型
    reloadResource: false,
    expectedVideo: {
      generation: 0,
      duration: "-",
    },
    libraryId: 1, //剪影中心项目id
    // 当前显示的预览视频
    crtShowVideo: {},
    generateLoading: false,
    crtShowVideoList: [],
    // 剪辑数据
    clipJSON: {
      title: "",
      id: -1, // 剪辑id
      edit_model: 1, // 剪辑模型  1-智能剪辑，2-一键成片，3-模板剪辑，4-脚本剪辑，5-图文剪辑）
      merchant_library_id: -1, // 项目ID
      aspect_ratio: "9:16", // 画面比例
      background_filling: 1, // 背景填充：1、2
      // 字幕
      subtitle_config: {
        open: 1,
        font: null,
        font_size: 32,
        material_url: null,
        width: 400,
        height: 200,
        css: "b {font-family:'HappyZcool-2016';text-align:center;font-size:32px;color: #FFF000;background:transparent ;opacity: 1;}",
        color: "#FFF000",
        background: "",
        opacity: 1,
        align_type: "center",
        verticle_position: "center",
      },
      script_data: {
        title: "自定义",
        audio_config: {
          //音频配置
          speed: 0,
          volume: 5,
          voice_id: 60,
          voice_type: 101004,
          gender_type: "male",
          emotion_category: "neutral",
          emotion_intensity: 150,
          emotion_style_key: "neutral",
          name: "智云-阅读男声（中性）",
        },
        subtitle_config: {
          //字幕位置和效果
          html: "<p>{{ CONTENT }}</p>", //{{ CONTENT }} 固定元素，其他的随意修改
          css: "p {font-family: 'HappyZcool-2016','HappyZcool-2016';font-size:32px;color: #FFF000;background:transparent;opacity: 1;text-align: center;}",
          open: 1,
          font: "",
          font_size: 32,
          material_url: null,
          width: 180, //以像素为单位设置HTML资产边界框的宽度。文本将换行以填充边界框。默认可以为 0
          height: 30, //以像素为单位设置HTML资产边界框的高度。如果文本和元素超过边界框的高度，它们将被遮罩。。默认可以为 0
          color: "#FFF000",
          background: "", //使用在HTML边界框后面应用背景色。使用十六进制颜色表示法设置文本颜色。通过设置十六进制字符串的前两个字符（与HTML相反）来支持透明度，即#80ffffff将为白色，透明度为80%[默认为“transparent”]。
          position: "center", //将HTML放置在HTML区域内的九个预定义位置之一[default to center].[top\topRight\right\bottomRight\bottom\bottomLeft\left\topLeft\center]
          verticle_position: "center",
          opacity: 1, //透明度（0-1,支持0.01）1-是不透明，0-是完全透明
          config: {
            x: 0, // 用了（不能小于 -1 ，不能大于 1）
            y: -0.22, // 用了（不能小于 -1 ，不能大于 1）
            transition_in: "", //进入过度
            transition_out: "", //出过度
            effect: "", //特效
            position: "center", //针对文字对应的 Clip （共 9 个位置，默认 center）
            start: 0, //开始时间，支持0.01 步长 [注意 封面这边就不需要传递这个参数
            length: 5, //播放时长
          },
        },
        subtitle_status: "on",
      },
      volume: {
        // 音量(注意，由于SDK音量是 0-1，所以前端传递必须是：0-100，然后使用的时候都要÷100)，必须
        bgm_volume: 50, // 背景音量 -对应 音乐 的 背景声音
        audio_volume: 100, // 音频音量--对应口播的解说音频
        scene_volume: 100, // 场景音量 --暂未对上号
        video_volume: 50, // 视频音量 --对应素材里的 视频原声
      },
      bgm_mode: "custom", // 背景音乐模式：custom-自定义，random-随机，必须
      bgm_scenes: [],
      bgm: [],
      // 口播
      audio: [],
      // 场景数据
      resource_data: [],
      effect_filter: {
        // 颜色调整
        color: {
          contrast: 0, // 对比度
          saturation: 0, // 饱和度
          brightness: 0, // 亮度
          tint: 0, // 色调
          temperature_ratio: 0, // 色温强度
          kelvin_temperature: 6000, // 色温
        },
      },
      effects: [],
      // 视频->贴纸
      sticker_config: [],
      cover_config: [],
      // 文字
      whole_subtitle_config: [],

      // 一键成片配置
      ai_compose_config: {
        ai_data: {
          content: "",
          num: 1, //AI生成条数
          // system_message_type: "SPEAKER_MASTER",
          style: "",
          freedom: "",
        },
        num: 5, //计划剪辑数量 对应
        video_volume: false, //视频原声 ，默认关闭
        audio_volume: true, //智能配音 ，默认开启
        title: true, //视频标题 ，默认开启
        subtitle: true, //视频字幕 默认开启
        bgm_volume: true, //背景音乐 默认开启
      },

      // 模板剪辑配置
      use_random_template: false,
      template_ids: [],
    },
    versionInfo: {}, // 会员权益
    selectTemplate: {
      durationKey: 0,
      labelKey: 0,
      duration: "全部",
      label: "全部",
    },
    // 视频混剪参数
    VideoMashup: {},

    // 字幕与配音抽屉中维护的数据
    Subtitles: [
      {
        type: 2, // 混剪模式 （0-单镜头混剪【当前镜头组，只挑选一个素材参与视频组合】，2-智能混剪 【当前镜头组的素材将切片后，随机参与视频组合】）
        name: "视频组_1", // 场景镜头名称
        volume: false, // 素材音量
        // 文本标题配置
        text_config: [
          {
            text: "",
            flower_id: "",
            // font: '',
            color: "rgba(255,255,255)",
            bg_color: "",
            font_size: "10",
            bold: 0,
            italic: 0,
            x: "0.5",
            y: "0.8",
            start_time: "", // 标题开始播放时间（单位：毫秒，音频转字幕时使用）
            alignment: "left",
            underline: "",
            text_duration: 1000, // 标题持续时长（单位：毫秒）
          },
        ],
        // 字幕和口播配置(多组)
        tts_config: [
          {
            tab_id: "text", //配置类型：text-手动设置字幕，audio-音频生成字幕
            audio_url: "", //音频地址
            img: "https://local.kuaijingai.com/public_web/static/images/workAi/voice/icon-women.png",
            name: "智聆",
            // 字幕格式(多组)
            iccts: [
              {
                elements: [
                  {
                    type: "", // type,text-文字，mute-静音,pause-停顿,phoneme-修改发音，number-数字读音
                    text: "",
                    content: "", // 修改发音的文字
                    ph: "", // 修改后的发音
                    breakTime: "", // 停顿时长
                    interpretAs: "", // number-数字读法，digits-序列读法，telephone-电话读法
                  },
                ],
                start_time: "", // 字幕开始播放时间（单位：毫秒，音频转字幕时使用）
                end_time: "", // 字幕播放结束时间（单位：毫秒，音频转字幕时使用）
              },
            ],
            showVoice: true, // 配音设置，true-开，false-关
            showSubtitle: true, // 字幕设置
            tone_id: 101002, // 音色id
            emotion_category: 100, // 情感程度
            speed: "0", // 语速
            volume: 6, // 音量
            duration: "",
            start_time: "",
            subtitle: [
              {
                text: "",
                ssml: "<speak></speak>",
                // font: "7028804401003380749",
                audio_url: "",
                font_size: "10",
                flower_id: "",
                bg_color: "",
                color: "#ffffff",
                bold: 0,
                italic: 0,
                x: "0.5",
                y: "0.8",
                start_time: 0,
                end_time: 0,
                alignment: "left",
                underline: 0,
                subtitle_id: "",
              },
            ],
          },
        ],

        time_strategy: {
          // 时长设置=>决定镜头组以哪个元素的时长为准
          type: 0, // 时长类型设置：（0-视频原始时长，1-随音频，视频自动变速 ，2-随音频，视频智能截取 ，3-固定时长，智能去重）
          fixed_time: 3000, //类型为 3-固定时长，智能去重 时有效
        },
        // 素材列表
        material_list: [],
      },
      {
        type: 2, // 混剪模式 （0-单镜头混剪【当前镜头组，只挑选一个素材参与视频组合】，2-智能混剪 【当前镜头组的素材将切片后，随机参与视频组合】）
        name: "视频组_2", // 场景镜头名称
        volume: false, // 素材音量
        // 文本标题配置
        text_config: [
          {
            text: "",
            flower_id: "",
            // font: '',
            color: "rgba(255,255,255)",
            bg_color: "",
            font_size: "10",
            bold: 0,
            italic: 0,
            x: "0.5",
            y: "0.8",
            start_time: "", // 标题开始播放时间（单位：毫秒，音频转字幕时使用）
            alignment: "",
            underline: "",
            text_duration: 1000, // 标题持续时长（单位：毫秒）
          },
        ],
        // 字幕和口播配置(多组)
        tts_config: [
          {
            tab_id: "text", //配置类型：text-手动设置字幕，audio-音频生成字幕
            audio_url: "", //音频地址
            img: "https://local.kuaijingai.com/public_web/static/images/workAi/voice/icon-women.png",
            name: "智聆",
            // 字幕格式(多组)
            iccts: [
              {
                elements: [
                  {
                    type: "", // type,text-文字，mute-静音,pause-停顿,phoneme-修改发音，number-数字读音
                    text: "",
                    content: "", // 修改发音的文字
                    ph: "", // 修改后的发音
                    breakTime: "", // 停顿时长
                    interpretAs: "", // number-数字读法，digits-序列读法，telephone-电话读法
                  },
                ],
                start_time: "", // 字幕开始播放时间（单位：毫秒，音频转字幕时使用）
                end_time: "", // 字幕播放结束时间（单位：毫秒，音频转字幕时使用）
              },
            ],
            showVoice: true, // 配音设置，true-开，false-关
            showSubtitle: true, // 字幕设置
            tone_id: 101002, // 音色id
            emotion_category: 100, // 情感程度
            speed: "0", // 语速
            volume: 6, // 音量
            duration: "",
            start_time: "",
            subtitle: [
              {
                text: "",
                ssml: "<speak></speak>",
                // font: "7028804401003380749",
                audio_url: "",
                font_size: "10",
                flower_id: "",
                bg_color: "",
                color: "#ffffff",
                bold: 0,
                italic: 0,
                x: "0.5",
                y: "0.8",
                start_time: 0,
                end_time: 0,
                alignment: "left",
                underline: 0,
                subtitle_id: "",
              },
            ],
          },
        ],

        time_strategy: {
          // 时长设置=>决定镜头组以哪个元素的时长为准
          type: 0, // 时长类型设置：（0-视频原始时长，1-随音频，视频自动变速 ，2-随音频，视频智能截取 ，3-固定时长，智能去重）
          fixed_time: 3000, //类型为 3-固定时长，智能去重 时有效
        },
        // 素材列表
        material_list: [],
      },
    ],
    // 全局全局字幕配音中维护的数据
    Global_tts_config: {
      type: 0, // 1-使用全局字幕配音，0-不使用全局字幕配音
      configs: [
        {
          tab_id: "",
          audio_material_id: "",
          audio_url: "",
          iccts: [
            {
              elements: [
                {
                  type: "",
                  text: "",
                  content: "",
                  ph: "",
                  breakTime: "",
                  interpretAs: "",
                },
              ],
              start_time: "",
              end_time: "",
            },
          ],
          showVoice: true,
          showSubtitle: true,
          tone_id: "",
          emotion_category: "",
          emotion_intensity: "",
          speed: "",
          volume: "",
          duration: "",
          start_time: "",
          subtitle: [
            {
              text: "",
              ssml: "",
              font: "",
              font_size: "",
              flower_id: "",
              bg_color: "",
              color: "",
              bold: "",
              italic: "",
              x: "",
              y: "",
              start_time: "",
              end_time: "",
              alignment: "",
              underline: "",
            },
          ],
        },
      ],
    },
    // 当前设置的镜头组
    currentIndex: {
      index: 0,
    },
    // 当前编辑的视频组tts_config的id
    current_tts_id: "",

    // 当前编辑的全局tts_id
    global_edit_tts_id: "",

    // 当前编辑的光标位置信息
    line_msg: {},

    // 字幕项当前播放video的状态
    VideoPlayingData: {
      isPlay: false, // 是否播放
      audio_url: "",
      reset: true, // 是否从头播放
      changeUrl: false, // 是否改变url
    },

    // 当前富文本正在编辑的 subtitle项的信息
    editSubtitleData: {
      // id: '',
      // text:''
    },

    // 当前用户选择选区的信息
    selectionsData: {
      // text: '; // 总的文本内容
      // selectedNodes: []; // 选择节点数量
    },

    // 数据是否发生变化
    VideoMashupChange: false,
    // 花字列表
    // FlowerList: [],
    FlowerArr: [],
    // 默认花字列表
    FlowerDefaultArr: null,

    // 字体列表
    fontList: [],
    /**
     * @description: ai 生成图片素材 异步开关, 每次轮询都会判断这个开关是否是开启状态
     * true: 允许生成, false:结束轮询
     */
    AiCreatSwitch: false,

    /**
     * @description: 模板内 ai 生成图片素材 异步开关, 每次轮询都会判断这个开关是否是开启状态
     * true: 允许生成, false:结束轮询
     * @
     */

    TemplateAiCreatSwitch: false,
    // 全局字幕配音, 正在修改的tts项的id
    globalTtsCurrent_id: "",
    defaultVoiceData: {}, //默认音色
    sceneCreationTexts: [], //AI创作内容文本
    sceneCreationTitles: [], //AI创作文本标题
    sceneCreationSubtileTitles: [], // 副标题

    pageData:{}, //分页缓存
    intelligentSplittingData:{}, //视频拆分选择的素材
    extractTextData:{}, //视频提取文字
    applicationMaterialData:{}, //应用素材数据
  },
  mutations: {
    SET_WORK_AI_CONFIG: (state, data) => {
      state.work_ai_config = data;
    },
    SET_GLOBALTTS_CURRENT_ID: (state, id) => {
      state.globalTtsCurrent_id = id;
    },
    // 修改ai 生成素材轮询开关
    SET_AICREAT_SWITCH: (state, payload) => {
      state.AiCreatSwitch = payload;
    },
    // 修改模板 生成素材轮询开关
    SET_TemplateAiCreatSwitch_SWITCH: (state, payload) => {
      state.TemplateAiCreatSwitch = payload;
    },
    // 存放字体列表数据
    SET_FONTFAMILY_DATA: (state, payload) => {
      state.fontList = payload;
    },
    // 模板筛选条件
    SET_SELECT_TEMPLATE: (state, payload) => {
      Object.assign(state.selectTemplate, {
        ...payload,
      });
    },
    // 基础信息
    SET_CLIP_INFO: (state, payload) => {
      Object.assign(state.clipJSON, {
        ...payload,
      });
      console.log("CLIP_JSON", state.clipJSON);
    },
    SET_DRAG_STATUS: (state, object) => {
      return new Promise((resolve, reject) => {
        state.dragStatus = object;
        resolve();
      });
    },
    SET_EXPECTED_VIDEO: (state, object) => {
      Object.assign(state.expectedVideo, object);
      // state.expectedVideo = object;
    },
    SET_LIBRARY_ID: (state, libraryId) => {
      state.clipJSON.merchant_library_id = libraryId;
    },
    // 场景数据
    SET_CLIP_JSON_RESOURCE_DATA: (state, payload) => {
      Object.assign(state.clipJSON, {
        // resource_data: payload.map((item, index) => ({ sn: index, ...item })),
        resource_data: payload,
      });
      console.log("RESOURCE_DATA", state.clipJSON);
    },
    // bgm数据
    SET_CLIP_JSON_BGM_DATA: (state, payload) => {
      Object.assign(state.clipJSON, {
        bgm: payload,
      });
      console.log("BGM_DATA", state.clipJSON);
    },
    // 口播数据
    SET_CLIP_JSON_AUDIO_DATA: (state, payload) => {
      Object.assign(state.clipJSON, {
        audio: payload,
      });
      console.log("AUDIO_DATA", state.clipJSON);
    },
    // 音量数据
    SET_CLIP_JSON_VOLUME: (state, payload) => {
      Object.assign(state.clipJSON.volume, payload);
      console.log("VOLUME_DATA", state.clipJSON);
    },
    // 颜色数据
    SET_CLIP_JSON_COLOR: (state, payload) => {
      Object.assign(state.clipJSON.effect_filter.color, payload);
      console.log("ColorData", state.clipJSON);
    },
    // 特效数据
    SET_CLIP_JSON_EFFECTS: (state, payload) => {
      const effectIndex = state.clipJSON.effects.findIndex(
        (item) => item.type === payload.type
      );

      if (effectIndex >= 0) {
        if (payload.params) {
          state.clipJSON.effects.splice(effectIndex, 1, payload);
        } else {
          state.clipJSON.effects.splice(effectIndex, 1);
        }
      } else {
        if (payload.params) {
          state.clipJSON.effects.push(payload);
        }
      }

      console.log("EffectsData", state.clipJSON);
    },
    //文字数据
    SET_CLIP_JSON_WORD: (state, payload) => {
      state.clipJSON.whole_subtitle_config = payload;
    },
    //封面数据
    SET_CLIP_JSON_COVER: (state, payload) => {
      state.clipJSON.cover_config = payload;
    },
    //贴纸数据
    SET_CLIP_JSON_STICKER: (state, payload) => {
      state.clipJSON.sticker_config = payload;
    },
    //当前播放的预览视频
    SET_CRT_SHOW_VIDEO: (state, payload) => {
      state.crtShowVideo = payload;
    },
    // loading
    SET_GENERATE_LOADING: (state, payload) => {
      state.generateLoading = payload;
    },
    // 全局文本标题
    SET_GENERATE_GLOBALTITLE: (state, payload) => {
      state.VideoMashup.global_text_config.type = payload.value;
    },
    // 全局字幕配音
    SET_GENERATE_GLOBALVIDEO: (state, payload) => {
      state.VideoMashup.global_tts_config.type = payload.value;
    },
    // 全局转场摄者
    SET_GENERATE_GLOBALTran: (state, payload) => {
      state.VideoMashup.transition_config.type = payload.value;
    },
    // 全局滤镜
    SET_GENERATE_GLOBALFilter: (state, payload) => {
      state.VideoMashup.filter_config.type = payload.value;
    },
    // 全局背景色
    SET_GENERATE_GLOBALBg: (state, payload) => {
      state.VideoMashup.background.type = payload.value;
    },
    // 视频封面设置
    SET_GENERATE_GLOBALVideoBg: (state, payload) => {
      state.VideoMashup.cover_config.type = payload.value;
    },
    // 全局配乐
    SET_GENERATE_GLOBALBGM: (state, payload) => {
      state.VideoMashup.bgm_config.type = payload.value;
    },
    //组合预览列表
    SET_CRT_SHOW_VIDEO_LIST: (state, payload) => {
      state.crtShowVideoList = payload;
    },
    // 设置字幕
    SET_SUB_TITLE: (state, payLoad) => {
      Object.assign(state.clipJSON.subtitle_config, payLoad);
    },
    REFRASH_RESOURCE: (state, reload) => {
      state.reloadResource = reload;
    },
    UPDATE_RESOURCE_DATA: (state, payload) => {
      state.clipJSON.resource_data[payload.index].video = payload.data;
      console.log("UPDATE_RESOURCE_DATA", state.clipJSON);
    },

    // 会员权益
    SET_VERSION_INFO: (state, info) => {
      // console.log(info,'用户套餐信息!!!!');
      
      state.versionInfo = info;
    },
    // 设置脚本数据
    SET_SCRIPT_DATA: (state, data) => {
      state.clipJSON.script_data = data;
    },
    // 一键成片
    SET_AI_COMPOSE_CONFIG: (state, payload) => {
      Object.assign(state.clipJSON.ai_compose_config, payload);
      console.log("AiComposeConfigData", state.clipJSON);
    },

    // 初始化视频混剪数据
    SET_VIDEOMASHUP: (state, data) => {
      Object.assign(state.VideoMashup, { ...data });
      console.log("VideoMashup", state.VideoMashup);
    },
    // 修改某项数据
    SET_VIDEOMASHUP_ITEM: (state, data) => {
      let type = Object.prototype.toString.call(data.value);
      type == "[object Object]"
        ? (() => {
            state.VideoMashup[data.key] = Object.assign(
              state.VideoMashup[data.key],
              data.value
            );
          })()
        : (state.VideoMashup[data.key] = data.value);

      console.log(state.VideoMashup, "修改之后的数据");
    },
    // 移除视频混剪数据
    REMOVE_VIDEOMASHUP_DATA: (state) => {
      state.VideoMashup = {};
    },

    // 初始化字幕与配音抽屉数据
    INIT_SUBTITLES_DATA: (state, data) => {
      state.Subtitles = JSON.parse(JSON.stringify(data));
    },
    // 修改某个抽屉中的开始时间
    MODIFY_DRAWER_START_TIME_DATA: (state, data) => {
      state.Subtitles[data.index].tts_config.forEach(
        (ele) => (ele[data.key] = data.value)
      );
      // state.Subtitles[data.index].tts_config[data.key] = data.value;
    },

    SETVIDEOPLAYING_DATA: (state, data) => {
      // debugger
      console.log(data, "修改值纸质纸盒子很自豪");
      let update = JSON.parse(JSON.stringify(state.VideoPlayingData));
      for (let k in data) {
        update[k] = data[k];
      }
      state.VideoPlayingData = update;
      // Object.assign({}, state.VideoPlayingData, data);
    },

    // 修改某个抽屉中的语音数据 - 并清空失效的音频数据
    MODIFY_DRAWER_VOICE: (state, data) => {
      const editType = state.Subtitles[state.currentIndex.index].tab_id;
      console.log(data, "修改的数据MODIFY_DRAWER_VOICE");
      state.Subtitles[data.index].tts_config.forEach((ele) => {
        if (editType == ele.tab_id) {
          ele[data.key] = data.value;
          if (data.key != "start_time") {
            ele.subtitle.forEach((ele) => {
              ele.audio_url = "";
              ele.duration = "";
            });
          }
        }
      });
      // state.Subtitles[data.index].tts_config[data.key] = data.value;
      console.log("修改某个抽屉中的语音数据", state.Subtitles);
    },

    // input 事件, 重置subtitle的某些数据
    MODIFY_DRAWER_SUBTITLE: (state, data) => {
      // const editType = state.Subtitles[state.currentIndex.index].tab_id
      state.Subtitles[state.currentIndex.index].tts_config.forEach((ele) => {
        // 当前编辑的tts_config
        if (ele.tts_id == data.tts_id) {
          const subtitleIndex = ele.subtitle.findIndex(
            (i) => i.subtitle_id == data.oldId
          );
          // 修改id, 清空音频数据, 修改ssml或者 对应的文本数据
          subtitleIndex != -1 &&
            (() => {
              ele.subtitle[subtitleIndex].ssml = data.ssml;
              ele.subtitle[subtitleIndex].text = data.text;
              ele.subtitle[subtitleIndex].subtitle_id = data.newId;
              ele.subtitle[subtitleIndex].audio_url = "";
              ele.subtitle[subtitleIndex].duration = "";
            })();
        }
      });
      // console.log('富文本修改仓库', state.Subtitles[state.currentIndex.index]);
    },

    // 往现在正在编辑的tts中, 添加一个 subtitle
    ADD_DRAWER_SUBTITLE: (state, data) => {
      const subtitle = baseSubtitle();
      state.Subtitles[state.currentIndex.index].tts_config.forEach((ele) => {
        if (ele.tts_id == state.current_tts_id) {
          ele.subtitle.push({
            ...subtitle,
            ...data,
          });
        }
      });
    },

    // state.Subtitles[data.index].tts_config[data.key] = data.value;

    // 存放当前编辑的tts_config的id
    MODIFY_TTS_ID: (state, data) => {
      state.current_tts_id = data;
    },

    // 存放当前编辑的全局tts_id
    MODIFY_GLOBAL_TTS_ID: (state, data) => {
      state.global_edit_tts_id = data;
    },

    // 存放当前编辑的富文本项的文本和id等各项信息
    SET_EDIT_SUBTITLE_DATA: (state, data) => {
      state.editSubtitleData = data;
    },

    // 存放当前节点的选区信息
    SET_SELECTION_DATA: (state, data) => {
      state.selectionsData = data;
    },

    // 移除字幕与配音数据
    REMOVE_SUBTITLES_DATA: (state, data) => {
      state.Subtitles = {};
    },
    // 修改抽屉中的subtitle 下面的字体信息
    MODIFY_SUBTITLES_DATA: (state, data) => {
      // debugger
      const editType = state.Subtitles[state.currentIndex.index].tab_id;
      state.Subtitles[state.currentIndex.index].tts_config.forEach((ele) => {
        // 如果编辑的类型相同, 修改此类型的值
        if (ele.tab_id == editType) {
          ele.subtitle.forEach((i) => {
            // i.material_path = data.material_path
            i.font_size = data.font_size;
            i.alignment = data.alignment;
            i.font_family = data.font_family;
            i.font_name = data.font_name;
            i.font_url = data.font_url;
            i.font_style = data.font_style;
            i.font_path = data.font_path;
            i.flower_id = data.flower_id;
            i.bg_color = data.bg_color;
            i.color = data.color;
            i.bold = data.bold;
            i.flower_config = JSON.parse(JSON.stringify(data.flower_config));
            i.preset_styles_config = JSON.parse(
              JSON.stringify(data.preset_styles_config)
            );
          });
        }
      });

      console.log("修改抽屉中的subtitle 下面的字体信息", state.Subtitles);
    },
    // 修改抽屉中的subtitle 下面的字体位置信息
    MODIFY_SUBTITLES_POSITION: (state, data) => {
      const editType = state.Subtitles[state.currentIndex.index].tab_id;
      state.Subtitles[state.currentIndex.index].tts_config.forEach((ele) => {
        if (ele.tab_id == editType) {
          ele.subtitle.forEach((i) => {
            // 如果是本项 则等于自己的x
            if (i.subtitle_id == data.id) {
              i.x = data.x;
            } else {
              i.x = data.showX - (i.showX - i.x);
            }
            i.y = data.y;
            i.showX = data.showX;
            // data.spanWidth && (i.spanWidth = data.spanWidth)
          });
        }
      });
    },

    // 修改全局字幕抽屉中的文字位置信息
    MODIFY_GLOBAL_SUBTITLES_POSITION: (state, data) => {
      state.Global_tts_config.configs.forEach((ele) => {
        if (ele.tab_id == data.configs_type) {
          ele.subtitle.forEach((item) => {
            if (item.subtitle_id == data.id) {
              item.x = data.x;
            } else {
              item.x = data.showX - (item.showX - item.x);
            }
            item.showX = data.showX;
            item.y = data.y;
          });
        }
      });
      // console.log(state.Global_tts_config.configs, "修改全局位置", data);
      console.log("修改全局位置", data.x);
    },

    // 修改抽屉中是是否开启字幕配置
    MODIFY_SHOW_SUBTITLE(state, data) {
      state.Subtitles[state.currentIndex.index].tts_config.forEach((ele) => {
        ele.showSubtitle = data;
      });
      console.log(
        state.Subtitles[state.currentIndex.index].tts_config,
        "修改字幕是否开启"
      );
    },
    // 修改抽屉中的 ttsConfig
    MODIFY_SUBTITLES_TTSCONFIG: (state, data) => {
      console.log(data, "保存音色");
      state.Subtitles[state.currentIndex.index].tts_config.forEach((ele) => {
        if (ele.tab_id == "text") {
          ele.emotion_category = data.emotion_category;
          (ele.speed = data.speed), // 语速
            (ele.volume = data.volume), // 音量
            (ele.tone_id = data.tone_id), // 选择的声音id
            (ele.emotion_intensity = data.emotion_intensity); //情感程度
          ele.emotion_category = data.emotion_category; //情感类型
          ele.img = data.img; //音色图片
          ele.name = data.name; //音色名称
          // 清除每一项的 音频缓存
          ele.subtitle.forEach((i) => {
            i.audio_url = "";
            i.duration = "";
            i.end_time = 0;
          });
        }
      });
      console.log(
        state.Subtitles[state.currentIndex.index].tts_config,
        "修改后的音色"
      );
    },

    // 修改抽屉中字幕的生成方式
    CHANGE_TTS_TAB_ID: (state, data) => {
      // state.Subtitles[state.currentIndex.index].tts_config.forEach((ele) => {
      //   ele.tab_id = data;
      // });
      state.Subtitles[state.currentIndex.index].tab_id = data;
    },
    // 切换镜头组index
    CHANGE_CURRENT_INDEX: (state, data) => {
      console.log(data, "indexdata");
      state.currentIndex = data;
      console.log(state.currentIndex, "indexindexindexindexindex");
    },
    // 修改 当前编辑的光标位置信息
    MODIFY_CURRENT_LINE_MSG: (state, data) => {
      state.line_msg = data;
    },
    // 初始化全局字幕与配音数据
    INIT_GLOBALTTSCONFIG_DATA: (state, data) => {
      console.log(data, "初始化全局数据");
      state.Global_tts_config = JSON.parse(JSON.stringify(data));
    },
    INIT_GLOBALTTSCONFIG_GLDATA: (state, data) => {
      // state.Global_tts_config = JSON.parse(JSON.stringify(data));
    },

    INIT_GLOBALTTSCONFIG_CONGIG: (state, data) => {
      state.VideoMashup.global_tts_config = JSON.parse(JSON.stringify(data));
    },

    // 修改全局字幕的生成方式
    CHANGE_GLOBALTTS_TAB_ID: (state, data) => {
      if (state.Global_tts_config.configs_type == "text") {
        state.Global_tts_config.configs_text.forEach((ele) => {
          ele.tab_id = data;
        });
      } else {
        state.Global_tts_config.configs_audio.forEach((ele) => {
          ele.tab_id = data;
        });
      }
    },
    // 移除全局字幕与配音数据
    REMOVE_GLOBALTTSCONFIG_DATA: (state, data) => {
      state.Global_tts_config = {};
    },
    // 修改全局字幕配音
    MODIFY_GLOBALTTSCONFIG_VOICE: (state, data) => {
      console.log(data, "wjkwjwjwjwkj修改全局字幕配音时间");
      const type = state.Global_tts_config.configs_type;
      state.Global_tts_config.configs.forEach((ele) => {
        if (ele.tab_id == type) {
          // 赋值对应数据, 置空失效的音频
          ele[data.key] = data.value;
          if (data.key != "start_time") {
            ele.subtitle.forEach((ele) => {
              ele.audio_url = "";
              ele.duration = "";
            });
          }
        }
      });
    },
    // 修改是否随机选项
    MODIFY_GLOBALTTSCONFIG_RANDOM: (state, data) => {
      state.Global_tts_config.isRandom = data;
    },

    // 修改抽屉中是是否开启全局字幕配置
    MODIFY_SHOW_GLOBALSUBTITLE(state, data) {
      const type = state.Global_tts_config.configs_type;
      state.Global_tts_config.configs.forEach((ele) => {
        ele.tab_id == type && (ele.showSubtitle = data);
      });
    },
    // 修改抽屉中的subtitle 下面的字体信息
    MODIFY_GLOBALSUBTITLES_DATA: (state, data) => {
      const type = state.Global_tts_config.configs_type;
      // debugger

      state.Global_tts_config.configs.forEach((ele) => {
        if (ele.tab_id == type) {
          ele.subtitle.forEach((i) => {
            // i.material_path = data.material_path;
            i.font_size = data.font_size;
            i.alignment = data.alignment;
            i.font_family = data.font_family;
            i.font_name = data.font_name;
            i.font_url = data.font_url;
            i.font_style = data.font_style;
            i.font_path = data.font_path;
            i.flower_id = data.flower_id;
            i.flower_config = data.flower_config;
            i.bg_color = data.bg_color;
            i.color = data.color;
            i.bold = data.bold;
            i.flower_config = JSON.parse(JSON.stringify(data.flower_config));
            i.preset_styles_config = JSON.parse(
              JSON.stringify(data.preset_styles_config)
            );
          });
        }
      });
    },
    // 修改全局抽屉中的 ttsConfig
    MODIFY_GLOSUBTITLES_TTSCONFIG: (state, data) => {
      state.Global_tts_config.configs.forEach((ele) => {
        if (ele.tab_id == "text") {
          ele.emotion_category = data.emotion_category;
          (ele.speed = data.speed), // 语速
            (ele.volume = data.volume), // 音量
            (ele.tone_id = data.tone_id), // 选择的声音id
            (ele.emotion_intensity = data.emotion_intensity); //情感程度
          ele.emotion_category = data.emotion_category; //情感类型
          ele.img = data.img; //音色图片
          ele.name = data.name; //音色名称
          ele.selectVoice = data.selectVoice;

          // 清除每一项的 音频缓存
          ele.subtitle.forEach((i) => {
            i.audio_url = "";
            i.duration = "";
            i.end_time = 0;
          });
        }
      });
    },

    // 改变数据变化的状态
    SYNCHRONIZATION_VIDEOMASHUP_CHANGE(state, data) {
      state.VideoMashupChange = data;
      console.log(data, " 数据发生改变");
    },

    // 存储花字数据
    // SET_FLOWER_LIST_DATA(state, data) {
    //   state.FlowerList = data;
    // },
    // 存储花字数据
    SET_FLOWER_ARR_DATA(state, data) {
      state.FlowerArr = data;
    },

    // 存储默认花字
    SET_FLOWER_ARR_DATA_DEFAULT(state, data) {
      state.FlowerDefaultArr = data;
    },

    // 设置全局音色配置
    SET_DEFAULT_VOICE_DATA(state, data) {
      state.defaultVoiceData = data;
      localStorage.setItem("defaultVoiceData", JSON.stringify(data));
    },
    // 设置AI创作文本内容
    SET_SCENE_CREATION_TEXTS(state, data) {
      state.sceneCreationTexts = data;
    },
    // 设置AI创作标题内容
    SET_SCENE_CREATION_TITLES(state, data) {
      state.sceneCreationTitles = data;
    },
    // 设置AI创作副标题内容
    SET_SCENE_CREATION_SUBTITLES(state, data) {
      state.sceneCreationSubtileTitles = data;
    },
    // 分页缓存
    SET_PAGE_DATA(state, data) {
      state.pageData = data;
    },
    // 视频拆分选择的素材
    SET_INTELLIGENT_SPLITTING_DATA(state, data) {
      state.intelligentSplittingData = data;
    },
    // 视频提取文字
    SET_EXTRACT_TEXT_DATA(state, data) {
      state.extractTextData = data;
    },
    // 获取创意工具应用素材数据
    SET_APPLICATION_MATERIAL_DATA(state, data) {
      state.applicationMaterialData = data;
    },
  },
  actions: {
    Getwork_ai_config({ commit, state }, payload) {
      return new Promise(async (resolve, reject) => {
      let org_id = utils.getOrgId();
      if (state.work_ai_config?.shotstack_driver) {
        resolve(state.work_ai_config);
      } else {
        if (org_id > 0) {
          try {
            request
              .get("/work_ai", "/config")
              .then((res) => {
                commit("SET_WORK_AI_CONFIG", res.list);
                resolve(res.list);
              })
              .catch((error) => {
                resolve({});
              });
          } catch (error) {
            resolve({});
          }
        } else {
          resolve({})
      }
      }
        });
    },
    SetClipInfo({ commit }, payload) {
      commit("SET_CLIP_INFO", payload);
    },
    SetDragStatus({ commit }, object) {
      commit("SET_DRAG_STATUS", object);
    },
    SetExpectedVideo({ commit }, object) {
      commit("SET_EXPECTED_VIDEO", object);
    },
    SetLibraryId({ commit }, libraryId) {
      commit("SET_LIBRARY_ID", libraryId);
    },
    SetClipJSONEffects({ commit }, payload) {
      commit("SET_CLIP_JSON_EFFECTS", payload);
    },
    SetClipJSONResourceData({ commit }, payload) {
      commit("SET_CLIP_JSON_RESOURCE_DATA", payload);
    },
    SetClipJSONBgmData({ commit }, payload) {
      commit("SET_CLIP_JSON_BGM_DATA", payload);
    },
    SetClipJsonAudioData({ commit }, payload) {
      commit("SET_CLIP_JSON_AUDIO_DATA", payload);
    },
    SetClipJSONVolume({ commit }, payload) {
      commit("SET_CLIP_JSON_VOLUME", payload);
    },
    SetClipJSONColor({ commit }, payload) {
      commit("SET_CLIP_JSON_COLOR", payload);
    },
    SetClipJSONWord({ commit }, payload) {
      commit("SET_CLIP_JSON_WORD", payload);
    },
    SetClipJSONCover({ commit }, payload) {
      commit("SET_CLIP_JSON_COVER", payload);
    },
    SetClipJSONSticker({ commit }, payload) {
      commit("SET_CLIP_JSON_STICKER", payload);
    },
    SetCrtShowVideo({ commit }, payload) {
      commit("SET_CRT_SHOW_VIDEO", payload);
    },
    SetGenerateLoading({ commit }, payload) {
      commit("SET_GENERATE_LOADING", payload);
    },
    SetGenerateGlobalTitle({ commit }, payload) {
      commit("SET_GENERATE_GLOBALTITLE", payload);
    },
    SetGenerateGlobalVideo({ commit }, payload) {
      commit("SET_GENERATE_GLOBALVIDEO", payload);
    },
    SetGenerateGlobalTran({ commit }, payload) {
      commit("SET_GENERATE_GLOBALTran", payload);
    },
    SetGenerateGlobalFilter({ commit }, payload) {
      commit("SET_GENERATE_GLOBALFilter", payload);
    },
    SetGenerateGlobalBg({ commit }, payload) {
      commit("SET_GENERATE_GLOBALBg", payload);
    },
    SetGenerateGlobalVideoBg({ commit }, payload) {
      commit("SET_GENERATE_GLOBALVideoBg", payload);
    },
    SetGenerateGlobalBgm({ commit }, payload) {
      commit("SET_GENERATE_GLOBALBGM", payload);
    },
    SetCrtShowVideoList({ commit }, payload) {
      commit("SET_CRT_SHOW_VIDEO_LIST", payload);
    },
    SetSubTitle({ commit }, payLoad) {
      commit("SET_SUB_TITLE", payLoad);
    },
    RefrashResource({ commit }, reload) {
      commit("REFRASH_RESOURCE", reload);
    },
    UpdateResourceData({ commit }, payLoad) {
      commit("UPDATE_RESOURCE_DATA", payLoad);
    },
    GetVersionInfo: ({ commit }) => {
      return new Promise((resolve) => {
        request
          .get("/work_ai", "/user/shotstack/version/info")
          .then((res) => {
            commit("SET_VERSION_INFO", res?.result);
            resolve(res?.result);
            // console.log(res, "获取用户信息成功");
          })
          .catch((err) => {
            console.log(err,'获取用户信息失败');
            
            resolve();
          });
      });
    },

    SetScriptData: ({ commit }, data) => {
      commit("SET_SCRIPT_DATA", data);
    },
    // 一键成片
    SetAiComposeConfigData: ({ commit }, payload) => {
      commit("SET_AI_COMPOSE_CONFIG", payload);
    },
    SetSelectTemplate: ({ commit }, payload) => {
      commit("SET_SELECT_TEMPLATE", payload);
    },

    // 初始化视频混剪数据
    SetVideoMashup: ({ commit }, payload) => {
      commit("SET_VIDEOMASHUP", payload);
    },

    // 修改某项视频混剪数据
    SetVideoMashupItem: ({ commit }, payload) => {
      commit("SET_VIDEOMASHUP_ITEM", payload);
    },
    // 移除视频混剪数据
    RemoveVideoMashupData: ({ commit }) => {
      commit("REMOVE_VIDEOMASHUP_DATA");
    },
    // 获取花字数据
    getFlowerListData: async ({ commit }) => {
      // const res = await request.get("/work_ai", "/user/shotstack/material/flower/list")
      const presetStyles = await request.get(
        "/work_ai",
        "/user/shotstack/material/presetStyles/list"
      );
      // commit("SET_FLOWER_LIST_DATA", res?.result);
      commit("SET_FLOWER_ARR_DATA", presetStyles?.result);
      commit("SET_FLOWER_ARR_DATA_DEFAULT", presetStyles?.default);

      console.log(presetStyles, "花字列表arr");
    },
    // 获取字体数据
    getFontFamily: async ({ commit }) => {
      return new Promise((resolve, reject) => {
        try {
          request
            .get("/work_ai", "/user/shotstack/material/fonts/list")
            .then((res) => {
              // res.result.map((item) => {
              //   item.label = item.name;
              //   item.value = item.material_url;
              //   // item.material_path = index
              // });

              res.result.forEach((item) => {
                item.label = item.name;
                item.value = item.material_url;
              });

              commit("SET_FONTFAMILY_DATA", res.result);
              res.result.forEach((font) => {
                const style = document.createElement("style");
                style.innerHTML = `
            @font-face {
              font-family: '${font.font_family}';
              src: url('${font.material_url}') format('truetype');
              }
              `;
                document.head.appendChild(style);
              });
              resolve();
            })
            .catch((error) => {
              reject(error);
            });
        } catch (error) {
          message.error("字体数据获取失败!");
          reject(error);
        }
      });
    },
    // 设置全局音色配置
    getRequestVoiceData: async ({ commit }) => {
      return new Promise((resolve, reject) => {
        try {
          request
            .get("/work_ai", "/user/shotstack/clip/default")
            .then((res) => {
              commit("SET_DEFAULT_VOICE_DATA", res.result.voice_config);
              resolve();
            })
            .catch((err) => {
              console.log(err);
              reject(err);
            });
        } catch (error) {}
      });
    },
    setPageData:({ commit }, pageData)=>{
      commit("SET_PAGE_DATA", pageData);
    },
    setSceneCreationSubtileTitles:({ commit }, data)=>{
      commit("SET_INTELLIGENT_SPLITTING_DATA", data);
    },
    setExtractTextData:({ commit }, data)=>{
      commit("SET_EXTRACT_TEXT_DATA", data);
    },
    setApplicationMaterialData:({ commit }, data)=>{
      commit("SET_APPLICATION_MATERIAL_DATA", data); 
    }
  },
  getters: {
    // 判断是否所有视频组的视频不为空
    allVideoGroup(state, payload) {
      return state.VideoMashup?.resource_data?.every((item) => {
        let filterMaterialList = item.material_list.filter((ele) => {
          return ele.material_url != "";
        });
        return filterMaterialList.length !== 0;
      });
    },
  },
};

export default shotstack;
